let canvas = document.getElementById("drawing_board");
let main=document.getElementById('main')
let ctx = canvas.getContext("2d");
let eraser = document.getElementById("eraser");
let clickRead = document.getElementById("click_read");
let brush = document.getElementById("brush");
let enlarge = document.getElementById('enlarge')
let reduction = document.getElementById('reduction');

let freeBrush = document.getElementById('free_brush');//自由绘制
let lineBrush = document.getElementById('line_brush');//直线绘制
let reactBrush = document.getElementById('react_brush');//矩形绘制
let cirlBrush = document.getElementById('cirl_brush');//圆形绘制

let aColorBtn = document.getElementsByClassName("color-item");

let selectColorNow = document.getElementById('select_color_now')
// let save = document.getElementById("save");
let selectBrush = document.getElementById('select_brush');
let reSetCanvas = document.getElementById("clear_con");

let eraserCon = document.getElementById('eraser_con');
// let clearCon=document.getElementById('clear_con')
let range = document.getElementById("range");
// 画笔粗细
let rangeCon = document.getElementById('range_con');
// 橡皮
let selectEraser = document.getElementById('select_eraser');
let imgRangeWrapPagin = document.getElementById('img_range_wrap_pagin');
let bar = document.getElementById('bar');
let smlImg = document.getElementById('sml_img');
let clear = false;//是否点击清除
let activeColor = '#ea3724';
let lWidth = 4;//画笔width
let isRead = true;//是否处于点读模式
let painting;//是否处于绘制模式
let brushType = 'freeBrush';// 画笔样式
let data= new Uint8ClampedArray([
    255, 0, 0, 128,
    255, 0, 0, 128,
    255, 0, 0, 128,
    255, 0, 0, 128
  ]);
let url =new ImageData(data, 2, 2);
let x;
let y;


autoSetSize(canvas);

// setCanvasBg('white');

// window.onbeforeunload = function(){
//     return "Reload site?";
// };

function autoSetSize(canvas) {
    canvasSetSize();

    function canvasSetSize() {
        let pageWidth = document.documentElement.clientWidth;
        let pageHeight = document.documentElement.clientHeight;

        canvas.width = pageWidth;
        canvas.height = pageHeight;
    }

    window.onresize = function () {
        canvasSetSize();
    }
}

// function setCanvasBg(color) {
// ctx.fillStyle = color;
// ctx.fillRect(0, 0, canvas.width, canvas.height);
// ctx.fillStyle = "black";
// }

function listenToUser(canvas) {
     painting=false;
    let lastPoint = { x: undefined, y: undefined };
    let zoom=1;
    let mainLeft;
    let mainTop;
    canvas.onmousedown = function (e) {
        // bar.style.display = 'block';
        selectBrush.style.display = 'none';
        selectEraser.style.display = 'none';
        imgRangeWrapPagin.style.display = 'none';
        smlImg.style.display = 'none';
        eraserCon.classList.add('active');
        reSetCanvas.classList.remove('active');

        if (isRead) {
            return;
        }
        painting=true;
      
            this.firstDot = ctx.getImageData(0, 0, canvas.width, canvas.height);//在这里储存绘图表面
            
            saveData(this.firstDot);
            
            let x = e.offsetX;
            let y = e.offsetY;
            lastPoint = { "x": x, "y": y };
            x = e.offsetX;
            y = e.offsetY;
            ctx.save();
            ctx.fillStyle = activeColor;
            ctx.strokeStyle = activeColor;
            drawCircle(x, y, 0);
        
        
    };
    canvas.onmousemove = function (e) {

        if (isRead) {
            return;
        }
        if (painting) {
            let x = e.offsetX;
            let y = e.offsetY;
            let newPoint = { "x": x, "y": y };
            // 判断 画笔类型
            if (brushType == 'lineBrush' && clear == false) {
                drawLine(lastPoint.x, lastPoint.y, newPoint.x, newPoint.y);

            } else if (brushType == 'freeBrush' && clear == false) {
                drawPencil(lastPoint.x, lastPoint.y, newPoint.x, newPoint.y, clear);
                lastPoint = newPoint;

            } else if (brushType == 'rectBrush' && clear == false) {
                drawRect(lastPoint.x, lastPoint.y, newPoint.x, newPoint.y);

            } else if (brushType == 'cirlBrush' && clear == false) {
                drawFreeCril(lastPoint.x, lastPoint.y, newPoint.x, newPoint.y);

            }
            // 清除
            if (clear == true) {
                
                clearRect(lastPoint.x, lastPoint.y, newPoint.x, newPoint.y);
                lastPoint = newPoint;
            }

        }
    };
    canvas.onmouseup = function (e) {
        painting = false;
        url = ctx.getImageData(0, 0, canvas.width, canvas.height);
        
    };

    canvas.mouseleave = function () {
        painting = false;
    }
    canvas.addEventListener('touchstart', function (e) {
        //  判断当前页面的缩放倍数
        if(main.style.transform=='scale(2)'){
            zoom=2;
        }else if(main.style.transform=='scale(4)'){
            zoom=4;
        }else if(main.style.transform=='scale(8)'){
            zoom=8;
        }else if(main.style.transform=='scale(10)'){
            zoom=10;
        }else{
            zoom=1;
        }
        mainLeft=Math.abs(Number(main.style.left.substring(0,main.style.left.length-2)));//main left
        mainTop=Math.abs(Number(main.style.top.substring(0,main.style.top.length-2)));//main top
        // bar.style.display = 'block';
        selectBrush.style.display = 'none';
        selectEraser.style.display = 'none';
        imgRangeWrapPagin.style.display = 'none';
        smlImg.style.display = 'none';
        eraserCon.classList.add('active');
        reSetCanvas.classList.remove('active');
        if (isRead) {
            return;
        }
        this.firstDot = ctx.getImageData(0, 0, canvas.width, canvas.height);//在这里储存绘图表面
        saveData(this.firstDot);
        painting = true;
        
        let x = (mainLeft+e.touches[0].clientX)/zoom;//点击x坐标
        let y = (mainTop+e.touches[0].clientY)/zoom;//点击Y坐标
        lastPoint = { "x": x, "y": y };
        ctx.save();
        ctx.fillStyle = activeColor;
            ctx.strokeStyle = activeColor;
        drawCircle(x, y, 0);
    })

    canvas.addEventListener('touchmove', function (e) {
        if (isRead) {
            return;
        }
        
        if (painting) {
            let x = (mainLeft+e.touches[0].clientX)/zoom;//手指的坐标X
            let y = (mainTop+e.touches[0].clientY)/zoom;//手指的坐标Y
            let newPoint = { "x": x, "y": y };
            // 判断画笔的类型
            if (brushType == 'lineBrush' && clear == false) {
                drawLine(lastPoint.x, lastPoint.y, newPoint.x, newPoint.y);

            } else if (brushType == 'freeBrush' && clear == false) {
                drawPencil(lastPoint.x, lastPoint.y, newPoint.x, newPoint.y, clear);
                lastPoint = newPoint;

            } else if (brushType == 'rectBrush' && clear == false) {
                drawRect(lastPoint.x, lastPoint.y, newPoint.x, newPoint.y);

            } else if (brushType == 'cirlBrush' && clear == false) {
                drawFreeCril(lastPoint.x, lastPoint.y, newPoint.x, newPoint.y);

            }
            if (clear == true) {
               
                clearRect(lastPoint.x, lastPoint.y, newPoint.x, newPoint.y);
                lastPoint = newPoint;
            }

        }

    })
    canvas.addEventListener('touchend', function (e) {
        painting = false;
        url = ctx.getImageData(0, 0, canvas.width, canvas.height);//存储绘制的路径
    })
}

// 橡皮擦
function clearRect(x1, y1, x2, y2) {
   
    ctx.lineWidth = 15;
    ctx.lineCap = "round";
    ctx.lineJoin = "round";
    ctx.save();
    ctx.globalCompositeOperation = "destination-out";
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
    ctx.stroke();
    ctx.closePath();
    ctx.clip();
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.restore();
}

function drawCircle(x, y, radius) {
    ctx.save();
    ctx.beginPath();
    cxt.fillStyle="#FF0000";
    ctx.arc(x, y, radius, 0, Math.PI * 2);
    ctx.fill();
    if (clear) {
        ctx.clip();
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.restore();
    }
}
// 自由绘制
function drawPencil(x1, y1, x2, y2) {

    ctx.lineWidth = lWidth;
    ctx.lineCap = "round";
    ctx.lineJoin = "round";
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
    ctx.stroke();
    ctx.closePath();

}
// 直线绘制
function drawLine(x1, y1, x2, y2) {
    ctx.lineWidth = lWidth;
    ctx.lineCap = "round";
    ctx.lineJoin = "round";
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.putImageData(url, 0, 0)
    ctx.beginPath();
    ctx.moveTo(x1, y1)
    ctx.lineTo(x2, y2);
    ctx.stroke();
    ctx.closePath();
}
// 矩形绘制
function drawRect(x1, y1, x2, y2) {
    ctx.lineWidth = lWidth;
    ctx.lineCap = "round";
    ctx.lineJoin = "round";
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.putImageData(url, 0, 0)
    ctx.beginPath();
    ctx.strokeRect(x1, y1, x2 - x1, y2 - y1);
    ctx.closePath();

}
// 原型绘制
function drawFreeCril(x1, y1, x2, y2) {
    ctx.lineWidth = lWidth;
    ctx.lineCap = "round";
    ctx.lineJoin = "round";
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.putImageData(url, 0, 0);
    ctx.beginPath();
    var rx = (x2 - x1) / 2;
    var ry = (y2 - y1) / 2;
    var r = Math.sqrt(rx * rx + ry * ry);
    ctx.arc(rx + x1, ry + y1, r, 0, Math.PI * 2);
    ctx.stroke();
    ctx.closePath();

}
// 画笔内容颜色的height
rangeCon.style.height = (248 / 30) * Number(range.value) + 'px';
range.oninput = function () {
    lWidth = this.value;
    rangeCon.style.height = (248 / 30) * Number(this.value) + 'px';
}

//橡皮檫
eraser.onclick = function () {
    clear = true;
    isRead = false;
    this.classList.add("active");
    brush.classList.remove("active");
    clickRead.classList.remove("active");
    selectEraser.style.display = 'block';
    selectBrush.style.display = 'none';
    // canvas.style.cursor='url(./images/test.png) -40 -40,pointer'
    canvas.style.cursor='crosshair';
};
// 橡皮擦
eraserCon.onclick = function () {
    clear = true;
    isRead = false;
    reSetCanvas.classList.remove('active');
    eraserCon.classList.add('active');
}

//画笔
brush.onclick = function () {
    clear = false;
    isRead = false;
    painting=true;
    selectBrush.style.display = 'flex';
    selectEraser.style.display = 'none';
    canvas.style.cursor='crosshair';
    this.classList.add("active");
    eraser.classList.remove("active");
    clickRead.classList.remove("active");
    listenToUser(canvas);
    getColor();
};
// 画笔选择
freeBrush.onclick = function () {
    isRead = false;
    clear = false;
    // painting=true;
    brushType = 'freeBrush';
    this.classList.add('active');
    lineBrush.classList.remove('active');
    reactBrush.classList.remove('active');
    cirlBrush.classList.remove('active');
}
// 选择直线画笔
lineBrush.onclick = function () {
    isRead = false;
    clear = false;
    // painting=true;
    brushType = 'lineBrush';
    this.classList.add('active');
    freeBrush.classList.remove('active');
    reactBrush.classList.remove('active');
    cirlBrush.classList.remove('active');
}
// 选择矩形画笔
reactBrush.onclick = function () {
    isRead = false;
    clear = false;
    // painting=true;
    brushType = 'rectBrush';
    this.classList.add('active');
    freeBrush.classList.remove('active');
    lineBrush.classList.remove('active');
    cirlBrush.classList.remove('active');
}
// 选择圆形画笔
cirlBrush.onclick = function () {
    isRead = false;
    clear = false;
    // painting=true;
    brushType = 'cirlBrush';
    this.classList.add('active');
    freeBrush.classList.remove('active');
    lineBrush.classList.remove('active');
    reactBrush.classList.remove('active');
}
//点读
clickRead.onclick = function () {
    isRead = true;
    this.classList.add("active");
    eraser.classList.remove("active");
    brush.classList.remove("active");
    // bar.style.display = 'block';
    selectBrush.style.display = 'none';
    selectEraser.style.display = 'none';
    imgRangeWrapPagin.style.display = 'none';
    canvas.style.cursor='pointer';
};

//清空
reSetCanvas.onclick = function () {

    ctxClear(ctx);
    this.classList.add('active')
    eraserCon.classList.remove('active');

    // setCanvasBg('white');
};
function ctxClear(ctx) {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    // url = ''
    url=new ImageData(data, 2, 2);
}
//
// save.onclick = function () {
//     let imgUrl = canvas.toDataURL("image/png");
//     let saveA = document.createElement("a");
//     document.body.appendChild(saveA);
//     saveA.href = imgUrl;
//     saveA.download = "zspic" + (new Date).getTime();
//     saveA.target = "_blank";
//     saveA.click();
// };

function getColor() {
    for (let i = 0; i < aColorBtn.length; i++) {
        aColorBtn[i].onclick = function () {
            for (let i = 0; i < aColorBtn.length; i++) {
                aColorBtn[i].classList.remove("active");
                this.classList.add("active");
                activeColor = this.style.backgroundColor;
                selectColorNow.style.backgroundColor = activeColor;
                ctx.fillStyle = activeColor;
                ctx.strokeStyle = activeColor;
            }
        }
    }
}

let historyDeta = [];

function saveData(data) {
    (historyDeta.length === 10) && (historyDeta.shift());// 上限为储存10步
    historyDeta.push(data);
}

//撤销
// undo.onclick = function () {
//     if (historyDeta.length < 1) return false;
//     ctx.putImageData(historyDeta[historyDeta.length - 1], 0, 0);
//     historyDeta.pop()
// };